package cn.springboot.erp.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.springboot.erp.commons.QueryParams;
import cn.springboot.erp.commons.ResponseResult;
import cn.springboot.erp.entity.Products;
import cn.springboot.erp.service.ProductsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.List;

@Api(tags = "商品管理")
@RestController
@RequestMapping("product")
public class ProductController {

    @Resource
    private ProductsService productService;

    @ApiOperation("商品名称列表")
    @GetMapping("productList")
    public ResponseResult productList(){
        LambdaQueryWrapper<Products> lambda = new QueryWrapper<Products>().lambda();
        lambda.select(Products::getId,Products::getName);
        List<Products> productsList = productService.list(lambda);
        return ResponseResult.Success().data("productList",productsList);
    }

    @ApiOperation("数据分页")
    @PostMapping("page")
    public ResponseResult listPage(@RequestBody QueryParams<Products> queryParams){
        return productService.listPage(queryParams);
    }

    @ApiOperation("商品类型列表")
    @GetMapping("categoriesList")
    public ResponseResult categoriesList(){
        return productService.categoriesList();
    }

    @ApiOperation("根据id查询")
    @GetMapping("selectById/{id}")
    public ResponseResult selectById(@PathVariable("id") Integer id){
        Products products = productService.getById(id);
        return ResponseResult.Success().data("product",products);
    }

    @ApiOperation("根据id删除")
    @GetMapping("deleteById/{id}")
    public ResponseResult deleteById(@PathVariable("id") Integer id){
        productService.removeById(id);
        return ResponseResult.Success().msg("删除成功");
    }

    @ApiOperation("添加或编辑")
    @PostMapping("insertOrUpdate")
    public ResponseResult insertOrUpdate(@RequestBody Products products){

        if (ObjectUtils.isNotNull(products.getId())){
            productService.saveOrUpdate(products);
            return ResponseResult.Success().msg("修改成功");
        }
        productService.saveOrUpdate(products);
        return ResponseResult.Success().msg("添加成功");
    }
}
